<?php

namespace App\Services\Api;

use App\Models\MsgGroup;
use App\Models\MsgInfo;
use App\Models\UserMsg;
use App\Services\Api\ApiService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * 消息接口模块
 * return ['status'=>1成功2失败,'msg'=>'提示信息','data'=>'返回数据']
 */
class MsgService extends ApiService
{

    /**
     * 消息列表
     * @param [type] $token
     * @method msgList
     * @author chengzhigang<1256699215@qq.com>
     */
    public function msgList($token)
    {
        try {
            //验证token
            $userInfo = Cache::get($token);
            if (empty($userInfo)) {
                return ['status' => 2, 'msg' => '请登录应用', 'data' => []];
            }
            $user_id = $userInfo['id'];
            $data = [];
            $unCreateData = $this->unCreateData($user_id); //未创建的消息
            $list = UserMsg::from('user_msg as a')->leftJoin('msg_info as b', 'a.msg_id', '=', 'b.id')
                ->where('a.user_id', $user_id)->whereBetween('a.status', [1, 2])->select('a.user_id', 'a.status as msg_status', 'b.*')
                ->orderBy('b.send_time', 'desc')->groupBy('a.id')->get()->toArray();
            $list = array_merge($unCreateData, $list);
            foreach ($list as $v) {
                if (!isset($data[$v['type']])) {
                    $data[$v['type']] = [];
                    $data[$v['type']]['title'] = MsgInfo::getTypeConfig($v['type'])['title'];
                    $data[$v['type']]['content'] = $v['content'];
                    $data[$v['type']]['logo'] = MsgInfo::getTypeConfig($v['type'])['logo'];
                    $data[$v['type']]['time'] = getTime($v['send_time']);
                    $data[$v['type']]['type'] = $v['type'];
                    $data[$v['type']]['unread_num'] = 0;
                }
                if ($v['msg_status'] == 1) {
                    $data[$v['type']]['unread_num'] += 1;
                }
            }
            return ['status' => 1, 'msg' => '请求成功', 'data' => ['list' => array_values($data)]];
        } catch (\Exception $e) {
            Log::info($e->getCode());
            Log::info($e->getFile());
            Log::info($e->getLine());
            Log::info('消息列表：' . $e->getMessage());
            writeErrorLog($e);
            return ['status' => 2, 'msg' => config('const.error'), 'data' => []];
        }
    }

    /**
     * 获取未创建的消息列表
     * @param [type] $user_id
     * @method unCreateData
     * @author chengzhigang<1256699215@qq.com>
     */
    private function unCreateData($user_id, $type = 0)
    {
        $newData = [];
        $where = [];
        $where['status'] = 2;
        if ($type) {
            $where['type'] = $type;
        }
        $newList = MsgInfo::where($where)->whereNotIn('id', function ($query) use ($user_id) {
            $query->select('msg_id')->from('user_msg')->where('user_id', $user_id);
        })->orderBy('send_time', 'desc')->get()->toArray();
        $msgIdsArr = array_column($newList, 'id');
        $unMsgIdsArr = MsgGroup::whereIn('msg_id', $msgIdsArr)->where('user_id', $user_id)->pluck('msg_id')->toArray();
        foreach ($newList as $k => $val) {
            $val['user_id'] = $user_id;
            $val['msg_status'] = 1;
            if ($val['user_type'] == 1) {
                $newData[] = $val;
            } elseif (in_array($val['id'], $unMsgIdsArr)) {
                $newData[] = $val;
            }
        }
        return $newData;
    }

    /**
     * 创建消息
     * @param [type] $data
     * @param [type] $status
     * @method createUserMsg
     * @author chengzhigang<1256699215@qq.com>
     * @param
     * @return
     */
    private function createUserMsg($data, $status = 2)
    {
        foreach ($data as $v) {
            UserMsg::create(['user_id' => $v['user_id'], 'msg_id' => $v['id'], 'status' => $status]);
        }
    }

    /**
     * 获取未读消息总数
     * @param [type] $token
     * @method getUnReadCount
     * @author chengzhigang<1256699215@qq.com>
     */
    public function getUnReadCount($token)
    {
        try {
            //验证token
            $userInfo = Cache::get($token);
            if (empty($userInfo)) {
                return ['status' => 2, 'msg' => '请登录应用', 'data' => []];
            }
            $user_id = $userInfo['id'];
            $unCreateData = $this->unCreateData($user_id); //未创建的消息
            $count = count($unCreateData);
            $unRead = UserMsg::from('user_msg')->where('user_id', $user_id)->where('status', 1)->count();
            $count += $unRead;
            return ['status' => 1, 'msg' => '请求成功', 'data' => ['count' => $count]];
        } catch (\Exception $e) {
            Log::info($e->getCode());
            Log::info($e->getFile());
            Log::info($e->getLine());
            Log::info('消息列表：' . $e->getMessage());
            writeErrorLog($e);
            return ['status' => 2, 'msg' => config('const.error'), 'data' => []];
        }
    }

    /**
     * 消息详情列表
     * @param [type] $token
     * @param [type] $per_page
     * @method msgInfoList
     * @author chengzhigang<1256699215@qq.com>
     */
    public function msgInfoList($token, $type, $page, $per_page)
    {
        try {
            //验证token
            $userInfo = Cache::get($token);
            if (empty($userInfo)) {
                return ['status' => 2, 'msg' => '请登录应用', 'data' => []];
            }
            $user_id = $userInfo['id'];
            $data = [];
            $unCreateData = $this->unCreateData($user_id, $type); //未创建的消息
            $this->createUserMsg($unCreateData, 2); //创建消息
            $list = UserMsg::from('user_msg as a')->leftJoin('msg_info as b', 'a.msg_id', '=', 'b.id')
                ->where('a.user_id', $user_id)->whereBetween('a.status', [1, 2])->select('a.user_id', 'a.status as msg_status', 'b.*')
                ->orderBy('b.send_time', 'desc')->paginate($per_page, ['*'], 'page', $page)->toArray();
            foreach ($list['data'] as &$val) {
                $val['logo'] = $val['logo'] ? config('const.img_url') . $val['logo'] : '';
            }
            return ['status' => 1, 'msg' => '请求成功', 'data' => ['list' => $list['data'], 'total' => $list['total']]];
        } catch (\Exception $e) {
            Log::info($e->getCode());
            Log::info($e->getFile());
            Log::info($e->getLine());
            Log::info('消息列表：' . $e->getMessage());
            writeErrorLog($e);
            return ['status' => 2, 'msg' => config('const.error'), 'data' => []];
        }
    }

    /**
     * 消息详情
     * @param [type] $token
     * @param [type] $id
     * @method msgDetail
     * @author chengzhigang<1256699215@qq.com>
     */
    public function msgDetail($token, $id)
    {
        try {
            //验证token
            $userInfo = Cache::get($token);
            if (empty($userInfo)) {
                return ['status' => 2, 'msg' => '请登录应用', 'data' => []];
            }
            $info = MsgInfo::where('id', $id)->select('id', 'title', 'content', 'logo', 'detail', 'send_time')->first();
            if (empty($info)) {
                return ['status' => 2, 'msg' => '消息不存在', 'data' => []];
            }
            return ['status' => 1, 'msg' => '请求成功', 'data' => $info->toArray()];
        } catch (\Exception $e) {
            Log::info($e->getCode());
            Log::info($e->getFile());
            Log::info($e->getLine());
            Log::info('消息详情：' . $e->getMessage());
            writeErrorLog($e);
            return ['status' => 2, 'msg' => config('const.error'), 'data' => []];
        }
    }

}
